﻿//-----------------------------------------------------------------------
// <copyright file="Future.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Base.Threading.Future
{
    using System;
    using System.ComponentModel;
    using TileTool.Threading.Future;

    /// <summary>
    /// Implementation of the future interface.
    /// </summary>
    public class Future : IFuture
    {
        #region Fields - Private

        /// <summary>
        /// State of the future object.
        /// </summary>
        private FutureState state = FutureState.None;

        /// <summary>
        /// Error value.
        /// </summary>
        private Exception error;

        /// <summary>
        /// Multicast delegate to call when the result is ready.
        /// </summary>
        private Action completed;

        /// <summary>
        /// Async operation we will use to trigger events on.
        /// </summary>
        private AsyncOperation op = null;

        /// <summary>
        /// Locking object for the class.
        /// </summary>
        private object lockObject = new object();

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor.
        /// </summary>
        public Future()
        {
            this.state = FutureState.Computing;
            this.op = AsyncOperationManager.CreateOperation(null);
        }

        #endregion

        #region Events - Public

        /// <summary>
        /// Progress event trigger via SetProgress().
        /// </summary>
        public event EventHandler<FutureProgressEventArgs> Progress;

        #endregion

        #region Properties - Public

        /// <summary>
        /// Gets if the future object has completed successfully.
        /// </summary>
        public bool IsCompleted
        {
            get
            {
                return this.State == FutureState.Completed;
            }
        }

        /// <summary>
        /// Gets if the future object has been canceled.
        /// </summary>
        public bool IsCanceled
        {
            get
            {
                return this.State == FutureState.Canceled;
            }
        }

        /// <summary>
        /// Gets if the state of the future object is in an error.
        /// </summary>
        public bool IsError
        {
            get
            {
                return this.State == FutureState.Error;
            }
        }

        /// <summary>
        /// Gets the state of the future object.
        /// </summary>
        public FutureState State
        {
            get
            {
                lock (this.LockObject)
                {
                    return this.state;
                }
            }
        }

        /// <summary>
        /// Gets the error value for the future object. Only valid when State
        /// returns FutureState.Error.
        /// </summary>
        public Exception Error
        {
            get
            {
                lock (this.LockObject)
                {
                    if (this.State != FutureState.Error)
                    {
                        throw new InvalidOperationException("You cannot get the error of the operation if it is not in an error state.");
                    }

                    return this.error;
                }
            }
        }

        #endregion

        #region Properties - Protected

        /// <summary>
        /// Gets the object we should use for locking access to the object.
        /// </summary>
        protected object LockObject
        {
            get
            {
                return this.lockObject;
            }
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Set the future object to be complete.
        /// 
        /// If this function is called multiple times, all calls after
        /// the first will be ignored.
        /// </summary>
        public virtual void SetComplete()
        {
            lock (this.LockObject)
            {
                if (this.State != FutureState.Computing)
                {
                    return;
                }

                this.state = FutureState.Completed;

                this.HandleCompleted();
            }
        }

        /// <summary>
        /// Set the future object into an error state.
        /// </summary>
        /// <param name="error">Exception for the error.</param>
        public void SetError(Exception error)
        {
            lock (this.LockObject)
            {
                if (this.State != FutureState.Computing)
                {
                    throw new InvalidOperationException("Future object can only be set to an error state while computing.");
                }

                this.state = FutureState.Error;
                this.error = error;

                this.HandleCompleted();
            }
        }

        /// <summary>
        /// Set the progress of the future object.
        /// </summary>
        /// <param name="status">Status for the progress.</param>
        /// <param name="progress">Progress amount. Must be -1 or 0 to 100.</param>
        public void SetProgress(string status, int progress = -1)
        {
            lock (this.LockObject)
            {
                if (this.State != FutureState.Computing)
                {
                    return;
                }

                EventHandler<FutureProgressEventArgs> temp = this.Progress;

                if (temp == null)
                {
                    return;
                }

                this.op.Post(
                    (object s) =>
                    {
                        FutureProgressEventArgs args = new FutureProgressEventArgs();

                        args.Status = status;
                        args.Progress = progress;

                        temp(this, args);
                    },
                    null);
            }
        }

        /// <summary>
        /// Implementation of the OnComplete() interface function.
        /// </summary>
        /// <param name="func">Method to call.</param>
        public void OnComplete(Action<IFuture> func)
        {
            if (func == null)
            {
                throw new ArgumentNullException("func", "Action must be non-null.");
            }

            lock (this.LockObject)
            {
                if (this.State == FutureState.Completed)
                {
                    func(this);
                    return;
                }

                this.AddCompleteAction(() => func(this));
            }
        }

        /// <summary>
        /// Function called to cancel the computation of the future result.
        /// 
        /// If the future object has already been computed or is in an error state,
        /// this function will do nothing.
        /// </summary>
        public void Cancel()
        {
            lock (this.LockObject)
            {
                if (this.State == FutureState.Computing)
                {
                    this.state = FutureState.Canceled;
                    this.HandleCompleted();
                }
            }
        }

        #endregion

        #region Methods - Protected

        /// <summary>
        /// Add the passed action to the completed actions delegate.
        /// 
        /// Assume the this object is locked.
        /// </summary>
        /// <param name="action">Action to add.</param>
        protected void AddCompleteAction(Action action)
        {
            this.completed += action;
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Called to trigger the completed event.
        /// </summary>
        private void HandleCompleted()
        {
            try
            {
                Action tempAction = this.completed;

                if (tempAction == null)
                {
                    return;
                }

                this.op.Post(
                    (object s) =>
                    {
                        tempAction();
                    },
                    null);
            }
            finally
            {
                this.op.OperationCompleted();
            }
        }

        #endregion
    }
}
